package com.car.order.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.car.commons.core.model.WoniuException;
import com.car.commons.core.util.JwtUtil;
import com.car.commons.web.util.RedisUtil;
import com.car.commons.web.util.StateUtil;
import com.car.commons.web.util.WebUtil;
import com.car.order.annotation.ServeOrderLogAnnotation;
import com.car.order.dto.goodOrderInfo.PayOrderForm;
import com.car.order.dto.serviceOrderInfo.ServiceOrderInfoCreatDto;
import com.car.order.dto.serviceOrderInfo.ServiceOrderInfoDto;
import com.car.order.entity.ServiceOrderInfo;
import com.car.order.entity.form.serveOrderInfo.*;
import com.car.commons.core.model.Result;
import com.car.order.entity.param.serviceOrderInfo.AddReviewParam;
import com.car.order.entity.param.serviceOrderInfo.ServiceOrderInfoInsertParam;
import com.car.order.exception.serveOrderInfo.ServeOrderInfoException;
import com.car.order.exception.serveOrderInfo.ServeOrderInfoExceptionCode;
import com.car.order.util.ServeOrderDescConstants;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import com.car.order.service.ServiceOrderInfoService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author 杜岷芫
 * @since 2024-08-29 10:40:34
 */
@RestController
@RequestMapping("/serviceOrderInfo")
@Api(tags = "服务订单信息")
public class ServiceOrderInfoController {

    @Resource
    private ServiceOrderInfoService serviceOrderInfoService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 分页查询
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "分页查询")
    @PostMapping("/findPage.md")
    public Result findPage(@RequestBody ServiceOrderInfoFindPageForm form) {
        String token = WebUtil.getToken();
        Integer clerkId = JwtUtil.getClerkId(token);
        form.setClerkId(clerkId);
        Page<ServiceOrderInfoDto> result = serviceOrderInfoService.findPage(form);
        return Result.getResult().setMsg("查询成功").setData(result);
    }

    /**
     * 根据用户id分页查询
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "根据用户id分页查询")
    @PostMapping("/findPageByUserId")
    public Result findPageByUserId(@RequestBody ServiceOrderInfoFindPageByUserIdForm form) {
        Page<ServiceOrderInfoDto> result = serviceOrderInfoService.findPageByUserId(form);
        return Result.getResult().setMsg("查询成功").setData(result);
    }

    /**
     * 列表查询
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "列表查询")
    @PostMapping("/findList")
    public Result findList(@RequestBody ServiceOrderInfoFindListForm form) {
        List<ServiceOrderInfo> result = serviceOrderInfoService.findList(form);
        return Result.getResult().setMsg("查询成功").setData(result);
    }

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询详情")
    @GetMapping("/{id}.md")
    public Result findById(@PathVariable("id") String id) {
        ServiceOrderInfo serviceOrderInfo = serviceOrderInfoService.findById(id);
        return Result.getResult().setMsg("查询成功").setData(serviceOrderInfo);
    }

    /**
     * 新增
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "新增服务订单")
    @PostMapping
    public Result insert(@RequestBody ServiceOrderInfoInsertForm form) throws Exception {
        ServiceOrderInfoInsertParam param = BeanUtil.toBean(form, ServiceOrderInfoInsertParam.class);
        String token = WebUtil.getRequest().getHeader("car-token");
        Integer userId = JwtUtil.getUserId(token);
        param.setUserId(userId);
        ServiceOrderInfoCreatDto serviceOrderInfoCreatDto = serviceOrderInfoService.insert(param);
        return Result.getResult().setMsg("操作成功").setData(serviceOrderInfoCreatDto);
    }

    /**
     * 支付订单
     *
     * @param form
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "支付订单")
    @PostMapping("/payOrder")
    public Result payOrder(@RequestBody PayOrderForm form) throws Exception {
        String token = WebUtil.getRequest().getHeader("car-token");
        String refreshToken = redisUtil.get(token);
        Integer userId = JwtUtil.getUserId(token);
        String s = serviceOrderInfoService.payOrder(form, userId);
        return Result.getResult().setMsg("跳转支付页面").setData(s);
    }

    /**
     * 支付宝回调接口
     *
     * @param req
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "支付宝回调接口")
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest req) throws Exception {
        HashMap<String, String> params = new HashMap<>();
        //获取支付宝请求的所有参数
        Map<String, String[]> reqParameterMap = req.getParameterMap();
        //通过迭代，获取所有
        for (Iterator<String> iterator = reqParameterMap.keySet().iterator(); iterator.hasNext(); ) {
            String name = iterator.next();
            String[] values = (String[]) reqParameterMap.get(name);//String[],因为value可能不只一个
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        serviceOrderInfoService.payNotify(params);
        return "SUCCESS";
    }


    /**
     * 修改
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "修改")
    @PutMapping
    public Result update(@RequestBody ServiceOrderInfoUpdateForm form) {
        ServiceOrderInfo serviceOrderInfo = serviceOrderInfoService.update(form);
        return Result.getResult().setMsg("操作成功").setData(serviceOrderInfo);
    }

    /**
     * 修改订单状态
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "修改订单状态")
    @PutMapping("/changeState.ty")
    public Result changeState(@RequestBody ServeOrderInfoChangeStateForm form) {
        ServiceOrderInfoDto serviceOrderInfoDto = serviceOrderInfoService.changeState(form);
        return Result.getResult().setMsg("操作成功").setData(serviceOrderInfoDto);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        serviceOrderInfoService.delete(id);
        return Result.getResult().setMsg("操作成功");
    }

    /**
     * 根据订单号查找订单
     * 并判断他是否为待服务
     */
    @GetMapping("/ByServeNum.ty")
    public Result findByServeNum(@RequestParam("serveNum") String serveNum) {
        ServiceOrderInfo byId = serviceOrderInfoService.getById(serveNum);
        if (!byId.getOrderState().equals(StateUtil.SERVE_ORDER_STATE_NOT_SERVED)) {
            throw new WoniuException(50, "该订单不是待服务状态");
        }
        return Result.getResult();
    }

    /**
     * 根据用户id查找订单
     * 并判断他是否为待服务
     * 只返回没有使用的订单
     */
    @GetMapping("/ByUserIdOrder.ty")
    public Result ByUserIdOrder(@RequestParam("userId") Integer userId) {
        QueryWrapper<ServiceOrderInfo> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        qw.eq("order_state", StateUtil.SERVE_ORDER_STATE_NOT_SERVED);
        List<ServiceOrderInfo> list = serviceOrderInfoService.list(qw);
        return Result.getResult().setData(list).setMsg("查询成功");
    }

    /**
     * 核验通过服务订单的核验码核验使用订单
     */
    @PutMapping("/verification/{verificationCode}")
    public Result verification(@PathVariable("verificationCode") String verificationCode) {
        ServiceOrderInfoDto serviceOrderInfoDto = serviceOrderInfoService.verification(verificationCode);
        return Result.getResult().setMsg("使用成功").setData(serviceOrderInfoDto);
    }

    @PutMapping("/addReview.ty")
    @ServeOrderLogAnnotation(desc=ServeOrderDescConstants.USER_EVALUATE)
    public Result addReview(@RequestBody AddReviewForm from) {
        String token = WebUtil.getToken();
        Integer userId = JwtUtil.getUserId(token);
        AddReviewParam param = BeanUtil.toBean(from, AddReviewParam.class);
        param.setUserId(userId);
        serviceOrderInfoService.addReview(param);
        return Result.getResult().setMsg("评论成功");
    }

    /**
     * 退款
     */
    @GetMapping("/tuikuan.ty")
    @ServeOrderLogAnnotation(desc = ServeOrderDescConstants.USER_TUI_KUAN)
    public Result tuikuan(@RequestParam("serveNum") String serveNum) {
        ServiceOrderInfo byId = serviceOrderInfoService.getById(serveNum);
        if (byId == null) {
            throw new ServeOrderInfoException(ServeOrderInfoExceptionCode.SERVE_ORDER_INFO_NOT_EXIST);
        }
        if (!byId.getOrderState().equals(StateUtil.SERVE_ORDER_STATE_NOT_SERVED)) {
            throw new ServeOrderInfoException(ServeOrderInfoExceptionCode.SERVE_INFO_STATE_ERROR);
        }
        return Result.getResult().setMsg("成功");
    }
    
}